<template>
    <!-- <a-menu mode="horizontal" v-model:selectedKeys="state.selectedKeys" :open-keys="state.openKeys" -->
    <a-menu mode="horizontal" v-model:selectedKeys="state.selectedKeys" :open-keys="state.openKeys"
        @openChange="(e: any) => onOpenChange(e as string[])" @click="handleClick">
        <template v-for="menu of storeMenus.asyncRoutes" :key="menu.path">
            <template v-if="menu.meta && menu.meta.menu_show">
                <template v-if="menu.path">
                    <menu-item :key="menu.path" style="text-align: center;">
                        <span class=" h-[62px] text-[18px] text-[#fff]">
                            {{ menu.meta.title }}</span></menu-item>
                </template>
            </template>
        </template>
    </a-menu>
</template>
<script lang="ts" setup>
import { useMenus } from '@/store/menus';
import { findWholeRouteByPath } from '@/utils/route.utils';
import { MenuProps, MenuItem } from 'ant-design-vue';
// import dayjs from 'dayjs'; 
import { RouteLocationNormalizedLoaded, RouteRecordRaw, useRoute, useRouter } from 'vue-router';
const router = useRouter();
const route = useRoute();
const storeMenus = useMenus();

const state = reactive<{ [key: string]: string[] }>({
    openKeys: [],
    rootSubmenuKeys: [],
    selectedKeys: [],
});
const onOpenChange = (openKeys: string[]) => {
    const latestOpenKey = openKeys.find(key => state.openKeys.indexOf(key) === -1);
    if (state.rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
        state.openKeys = openKeys;
    } else {
        state.openKeys = latestOpenKey ? [latestOpenKey] : [];
    }
};
const handleClick: MenuProps['onClick'] = menuInfo => {
    state.selectedKeys = [menuInfo.key.toString()];
    router.push({ path: menuInfo.key.toString() });
};

const fillRoute = (route: Array<RouteRecordRaw>) => {
    route.forEach(r => {
        if (r.meta && r.meta.menu_show) {
            state.rootSubmenuKeys.push(r.path);
        }
    });
};
const dynamic_route = (r: RouteLocationNormalizedLoaded) => {
    if (state.rootSubmenuKeys && state.rootSubmenuKeys.length > 0) {
        const info = state.rootSubmenuKeys.find(root => root === r.path)
        if (info) {
            state.selectedKeys = [r.path];
        } else {
            const res = findWholeRouteByPath(r.path, useMenus().asyncRoutes)
            if (res) {
                state.selectedKeys = [res.path]
            }
        }
    }
};
watch(route, newVal => {
    dynamic_route(newVal);
});
watch(
    () => storeMenus.asyncRoutes,
    val => {
        fillRoute(val);
    },
    {
        deep: true,
        immediate: true,
    }
);



onMounted(() => {
    dynamic_route(route);
});
</script>
<style lang="scss" scoped></style>
  